'use strict';

const BaseController = require('./base');

class CollectionController extends BaseController {
  get _service() {
    return 'collection';
  }

  // 判断是否已收藏过
  async isCollection() {
    const { ctx } = this;
    const { houseId, cid } = ctx.params();
    const isExist = await this._getService().isExist({ uid: ctx.userId, houseId, cid });
    if (isExist) {
      this.success({ flag: true });
    } else {
      this.success({ flag: false });
    }
  }

  async create() {
    const { ctx } = this;
    const { houseId, cid } = ctx.params();
    // 从所有数据中查找是否有该数据
    const isExist = await this._getService().isExist({ uid: ctx.userId, houseId, cid, paranoid: false });
    let result = null;
    // 如果存在 则恢复数据 如果无 则新增数据
    if (isExist) {
      result = await this._getService().restore({ uid: ctx.userId, houseId, cid });
    } else {
      result = await this._getService().create({ uid: ctx.userId, houseId, cid });
    }
    if (result) {
      this.success();
    } else {
      this.error('收藏失败');
    }
  }

  async destroy() {
    const { ctx } = this;
    const { houseId, cid } = ctx.request.body;
    const result = await this._getService().destory({ houseId, cid, uid: ctx.userId });
    if (result) {
      this.success();
    } else {
      this.error('取消收藏失败');
    }
  }

  // 获取登录人的收藏
  async index() {
    const { ctx } = this;
    const { pageIndex, pageSize } = ctx.params();
    const tempResult = await this._getService().findList({ uid: ctx.userId, pageIndex, pageSize });
    if (tempResult) {
      this.success(tempResult.data, tempResult.count);
    } else {
      this.error('获取收藏失败');
    }
  }

  // 获取自己民宿最受关注top5
  async statisticalCollectionHouse() {
    const { ctx } = this;
    const result = await this._getService().statisticalCollectionHouse({ uid: ctx.userId });
    if (result) {
      this.success(result.map(item => ({ ...item, value: +item['COUNT(*)'] })));
    } else {
      this.error('获取数据失败');
    }
  }

  // 获取自己论坛最受关注top5
  async statisticalCollectionComment() {
    const { ctx } = this;
    const result = await this._getService().statisticalCollectionComment({ uid: ctx.userId });
    if (result) {
      this.success(result.map(item => ({ ...item, name: item.title, value: +item['COUNT(*)'] })));
    } else {
      this.error('获取数据失败');
    }
  }

  // 获取所有民宿最受关注top5
  async statisticalCollectionHouseAll() {
    const result = await this._getService().statisticalCollectionHouseAll();
    if (result) {
      this.success(result.map(item => ({ ...item, value: +item['COUNT(*)'] })));
    } else {
      this.error('获取数据失败');
    }
  }

  // 获取所有论坛最受关注top5
  async statisticalCollectionCommentAll() {
    const result = await this._getService().statisticalCollectionCommentAll();
    if (result) {
      this.success(result.map(item => ({ ...item, name: item.title, value: +item['COUNT(*)'] })));
    } else {
      this.error('获取数据失败');
    }
  }
}

module.exports = CollectionController;
